class CustomUpdater < FeedTools::FeedUpdater
  require 'config/boot.rb'
  require 'vendor/plugins/acts_as_taggable/lib/acts_as_taggable.rb'
  ActiveRecord::Base.send(:include, ActiveRecord::Acts::Taggable)
  require 'vendor/plugins/acts_as_taggable/lib/tag.rb'
  require 'vendor/plugins/acts_as_taggable/lib/tagging.rb'
  require 'app/models/feed.rb'
  require 'app/models/item.rb'
  
  on_begin do
     self.feed_href_list = Feed.find(:all, :order =>"pubDate DESC").map{|f| f.link}
  end
  
  on_update do |feed, seconds|
    self.logger.info("Loaded '#{feed.href}'.")
    self.logger.info("=> Updated (#{feed.title}) in #{seconds} seconds.")
    rails_feed=Feed.find(:first, :conditions=>["link=?",feed.href])
    self.logger.info("=> Feed is #{rails_feed.description}")
    rails_feed.pubDate=feed.time if feed.time
    #rails_feed.title=FeedTools::HtmlHelper.unescape_entities(feed.title)
    #rails_feed.description=FeedTools::HtmlHelper.unescape_entities(feed.description)
    rails_feed.error_tag=0
    #rails_feed.site_url=feed.link
    rails_feed.save
    rails_feed.expire_items
    feed.entries.each do |item|
      rails_item=Item.find_or_create_by_guid(item.guid || item.link)     
      rails_item.update_attributes(
        {:title=>item.title, #FeedTools::HtmlHelper.unescape_entities(item.title),
        :pubDate=>item.time,
        :description=>item.description,# FeedTools::HtmlHelper.unescape_entities(item.description),
        :author=>item.author.name,
        :link=>item.link,
        :expired=>0})
      rails_feed.items<<rails_item
      item.categories.each do |cat|
        rails_cat=Category.find_or_create_by_name(cat.term)
        rails_cat.save
        rails_item.categories<<rails_cat
      end rescue nil
      rails_item.save
    end
    end
  
  on_error do |href, error|
    self.logger.info("Error updating '#{href}':")
    self.logger.info(error)
    rails_feed=Feed.find_by_link(href)
    rails_feed.error_tag=1 rescue nil
    rails_feed.save
  end

  on_complete do |updated_feed_hrefs|
  end
end
